package org.example.controller;

import org.example.model.Device;
import org.example.model.Login;

import org.example.model.Material;

import org.example.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController  //控制类 异步请求（json格式）
@CrossOrigin
@RequestMapping("/api/user")
public class LoginController {
    private final LoginService loginService;

    @Autowired
    public LoginController(LoginService loginService) {
        this.loginService = loginService;
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Login loginLogin) {
        System.out.println("到后短了");
        Login login = loginService.login(loginLogin.getUsername(), loginLogin.getPassword(), loginLogin.getRole());
        if (login != null) {
            return ResponseEntity.ok(login);
        } else {
            System.out.println("登录失败");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户名或密码或职务错误");

        }
    }

    // 查询用户姓名
    @GetMapping("/{id}")
    public String getNameById(@PathVariable String id) {
        return loginService.getNameById(Integer.valueOf(id));
    }

    // 注册用户
    @PostMapping
    public ResponseEntity<Object> addUser(@RequestBody Login login) {

        loginService.addUser(login);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    //修改密码
    @PutMapping("/{id}")
    public ResponseEntity<Void> updatePassword(
            @PathVariable int id,
            @RequestBody Login login) {
        // 确保路径ID与请求体ID一致（防止误操作）
        if (id != (login.getId())) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }

        boolean isUpdated = loginService.updatePassword(login) > 0;
        return isUpdated
                ? new ResponseEntity<>(HttpStatus.OK)
                : new ResponseEntity<>(HttpStatus.NOT_FOUND); // 未找到对应ID
    }
    //注销用户
    @DeleteMapping("/{id}")
    public ResponseEntity<Object> deleteUser(@PathVariable Integer id) {
        try {
            loginService.deleteUser(id);
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        } catch (Exception e) {

            return new ResponseEntity<>("注销用户异常: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

} 